from crum import get_current_user
from django.db import models
from pgcrypto import fields

from apps.client.models import Client
from apps.communication.types import MESSAGE_TYPES, MessageTypes, FROM_TYPES, FromTypes
from apps.core.models import GenericModel
from apps.users.models import User


# Create your models here.

class ProviderClientMessage(GenericModel):
    client = models.ForeignKey(Client, on_delete=models.CASCADE)
    content = models.TextField(null=True, blank=True)
    message_type = models.IntegerField(
        choices=MESSAGE_TYPES,
        default=MessageTypes.DEFAULT_MESSAGE.value
    )
    is_read = models.BooleanField(default=False)
    from_type = models.IntegerField(
        choices=FROM_TYPES,
        default=FromTypes.PROVIDER.value,
        null=True
    )

    def save(self, *args, **kwargs):
        user = get_current_user()
        if self._state.adding and isinstance(user, User):
            self.created_by = user
        elif isinstance(user, User):
            self.updated_by = user

        super(GenericModel, self).save(*args, **kwargs)

    class Meta:
        db_table = 'provider_client_messages'


class MessageFile(GenericModel):
    message = models.ForeignKey(
        ProviderClientMessage, on_delete=models.CASCADE, related_name='files')
    message_file = fields.CharPGPSymmetricKeyField(max_length=500, default="")
    file_name = models.TextField(max_length=500, null=True, blank=True)

    class Meta:
        db_table = 'message_files'
